package com.e3.web.widget.client;

import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.DomEvent;
import com.extjs.gxt.ui.client.widget.form.TriggerField;
import com.google.gwt.user.client.Element;

public class MyRefTextField<D> extends TriggerField<String> implements MyField<D> {
	
	private boolean isHide = false;

	private MyRefDialog<D> refWindow;

	public MyRefTextField() {
		super();
		autoValidate = false;
		this.setTriggerStyle("x-form-search-trigger");
	}

	public MyRefTextField(MyRefDialog<D> refWindow) {
		super();
		this.refWindow = refWindow;
		autoValidate = false;
		this.setTriggerStyle("x-form-search-trigger");
	}

	public void setRefDialog(MyRefDialog<D> refWindow) {
		this.refWindow = refWindow;
	}

	@Override
	protected void onRender(Element target, int index) {
		super.onRender(target, index);
		this.refWindow.setSize(300, 400);
		this.refWindow.setModal(true);
		this.refWindow.setRefTextField(this);
	}

	@Override
	protected void onTriggerClick(ComponentEvent ce) {
		super.onTriggerClick(ce);
		if (isReadOnly()) {
			return;
		}
		expand();
		getInputEl().focus();
	}

	protected void expand() {
		D v = getFieldValue();
		if (v != null) {
			refWindow.setRefValue(v);
		}
		
		refWindow.setVisible(true);
		refWindow.focus();
	}

	public D getFieldValue() {
		return refWindow.getRefValue();
	}
	
	@Override
	public String getValue() {
		return refWindow.getDisplayValue();
	}

	@SuppressWarnings("unchecked")
	public void setFieldValue(Object value) {
		refWindow.setRefValue((D)value);
		String dispValue = refWindow.getDisplayValue();
		if (dispValue != null) {
			setValue(dispValue);
		}
	}
	
	@Override
	protected boolean validateBlur(DomEvent ce, Element target){
		if(getFieldValue()==null){
			ce.stopEvent();
			return false;
		}
		return true;
	}
	
	@Override
	public void hide() {
		isHide = true;
		super.hide();
	}

	public boolean isHide() {
		return isHide;
	}
}
